!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!       Modulo de numeros aleatorios
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  module random1
    use rbf_type
    implicit none
    real (dp)                   :: carry
    integer                     :: i24,j24,iseed
    real (dp), dimension(24)    :: seed
  end module random1

module random_number2
  use rbf_type
  implicit none
  private
  public  ::  randx
  public  ::  ranf
contains

  function randx(iseed)
    use rbf_type
    implicit none   
    real (dp)              ::    randx
    integer   ,parameter   ::    m1=714025,ia=1366,ic=150889
    real (dp) , parameter  ::    rm=1.0/m1   
    integer                ::    iseed

    iseed=mod(ia*iseed+ic,m1)
    randx=iseed*rm
    if(randx<0.0)then
       stop 'random number is negative'
    endif
  end function randx
       
  function ranf(dummy)
    use rbf_type
    use random1

    implicit none
    integer               ::  dummy
    real (dp) , parameter ::  twop24=16777216.d0 , twom24 = 1.d0/twop24
    real (dp)             ::  rcarry,uni,ranf
  
    uni=seed(i24)-seed(j24)-carry
         
    if(uni<0.0)then
       uni=uni+1.d0
       carry=twom24
    else
       carry=0.d0
    endif
    seed(i24)  = uni
    i24        = i24-1

    if(i24==0) i24 = 24
    j24   = j24-1
    if(j24==0) j24 = 24
    rcarry=uni
    ranf=rcarry
  end function  ranf
end module random_number2
!...................................................................................
module ranftest
  use rbf_type
  public :: rantest
  public  ::  timer
contains
  
  subroutine rantest(iseeda)
    use rbf_type
    use random_number2
    use random1
    implicit none
    
    integer                  :: i,iseeda
    real (dp)     :: ran
    i24   =  24
    j24   =  10
    carry =  0.d0
    iseed = iseeda       
    do i = 1, 100
       ran = randx(iseed)   
    enddo
    do i = 1, 24
       seed(i) = randx(iseed)
    enddo
  end subroutine rantest


  subroutine restart_rand(iseed)
    use rbf_type
    use random1
    implicit none
    integer k,iseed
    open(11,file='rand.bin',form='binary',status='old',action='READ')    
    do k=1,24
       read(11) seed(k)
    end do
    read(11)i24
    read(11)j24
    read(11)carry
    rewind(11)
    close(11)
  end subroutine restart_rand

  subroutine rand_save(iseed)
    use rbf_type
    use random1
    implicit none
    integer k,iseed
    open(11,file='rand.bin',form='binary',status='old',access='append',action='write')
    do k=1,24
       write(11) seed(k)
    end do
    write(11)i24
    write(11)j24
    write(11)carry

    close(11)
    
  end subroutine rand_save
end module ranftest

subroutine RANDOM_NUMBER1(array_rn)
use rbf_type
use random_number2
use ranftest
use variable, only: iseed
implicit none
real(dp)  ,  dimension(*) :: array_rn
integer :: i

do i=1,6
   array_rn(i)=ranf(iseed)
enddo

end subroutine  RANDOM_NUMBER1
